<template>
  <div class="table-box grid">
    <div class="left-table">
      <ProTable
        ref="dictTypeProTableRef"
        :title="$t('message.dictTypeInfo.title')"
        :columns="dictTypeColumns"
        :request-api="dictTypeApi.page"
        :data-callback="dictTypeDataCallback"
        :init-param="dictTypeInitParam"
        @row-click="rowClick"
      >
        <template #tableHeader>
          <el-space class="align-container">
            <el-button type="success" :icon="CirclePlus" @click="openEditDictType('add', {})">
              {{ $t("message.dictTypeButton.add") }}
            </el-button>
            <el-input v-model="dictTypeInitParam.name" placeholder="类型名称" />
            <el-button type="primary" :icon="Search" @click="refreshDictType"> {{ $t("message.commonBtn.query") }} </el-button>
            <el-button type="info" :icon="Refresh" @click="resetDictType"> {{ $t("message.commonBtn.reset") }} </el-button>
          </el-space>
        </template>
        <template #operation="scope">
          <el-space>
            <el-button size="small" text type="primary" @click="openEditDictType('edit', scope.row)">
              <el-icon><Edit /></el-icon>
              {{ $t("message.commonBtn.edit") }}
            </el-button>
            <el-button size="small" text type="danger" @click="delDictType(scope.row)">
              <el-icon><Delete /></el-icon>
              {{ $t("message.commonBtn.delete") }}
            </el-button>
            <el-button type="success" text @click="openEditDictDataByTypeRow(scope.row)">
              <el-icon><CirclePlus /></el-icon>
              {{ $t("message.dictDataButton.add") }}
            </el-button>
          </el-space>
        </template>
      </ProTable>
      <EditDictType ref="editDictTypeRef" @refresh="refreshDictType" />
    </div>
    <div class="right-table">
      <ProTable
        ref="dictDataProTableRef"
        :columns="dictDataColumns"
        :request-api="getDictData"
        :data-callback="dictDataCallback"
        :request-auto="false"
      >
        <template #tableHeader>
          <el-space class="align-container">
            <el-button type="success" :icon="CirclePlus" @click="openEditDictData('add', {})">
              {{ $t("message.dictDataButton.add") }}
            </el-button>
            <el-input v-model="dictDataInitParam.dictDataName" placeholder="字典名称" />
            <el-button type="primary" :icon="Search" @click="refreshDictData"> {{ $t("message.commonBtn.query") }} </el-button>
            <el-button type="info" :icon="Refresh" @click="resetDictData"> {{ $t("message.commonBtn.reset") }} </el-button>
          </el-space>
        </template>
        <template #operation="scope">
          <el-space>
            <el-button size="small" text type="primary" @click="openEditDictData('edit', scope.row)">
              <el-icon><Edit /></el-icon>
              {{ $t("message.commonBtn.edit") }}
            </el-button>
            <el-button size="small" text type="danger" @click="delDictData(scope.row)">
              <el-icon><Delete /></el-icon>
              {{ $t("message.commonBtn.delete") }}
            </el-button>
          </el-space>
        </template>
      </ProTable>
      <EditDictData ref="editDictDataRef" @refresh="refreshDictData" />
    </div>
  </div>
</template>
<script lang="tsx" setup name="Dict">
import dictTypeApi from "@/api-services/apis/system/dictTypeApi";
import { DictData, DictType } from "@/api-services/models/system";
import { SqlSugarPagedList, UnifyResult } from "@/api-services/unifyResult";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { feature } from "@/utils/axios-utils";
import { CirclePlus, Refresh, Search } from "@element-plus/icons-vue";
import { ElMessageBox, TableColumnCtx } from "element-plus";
import { useI18n } from "vue-i18n";
import dictDataApi from "@/api-services/apis/system/dictDataApi";
import { NotificationError, NotificationSuccess, NotificationWarning } from "@/utils/notification";
const EditDictType = defineAsyncComponent(() => import("./component/editDictType.vue"));
const EditDictData = defineAsyncComponent(() => import("./component/editDictData.vue"));
const { t } = useI18n();
const dictTypeProTableRef = ref<ProTableInstance>();
const dictDataProTableRef = ref<ProTableInstance>();
const editDictTypeRef = ref<InstanceType<typeof EditDictType> | null>(null);
const editDictDataRef = ref<InstanceType<typeof EditDictData> | null>(null);
const dictTypeInitParam = reactive({ name: "" });
const choseDictType = ref<DictType.SysDictType>({});
const dictTypeDataCallback = (queryRes: UnifyResult<SqlSugarPagedList<DictType.SysDictType>>) => {
  const data = queryRes.data;
  return {
    items: data.items,
    totalCount: data.totalCount,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize
  };
};
const dictTypeColumns: ColumnProps<DictType.SysDictType>[] = [
  {
    prop: "name",
    label: t("message.dictTypeInfo.name")
  },
  {
    prop: "code",
    label: t("message.dictTypeInfo.code")
  },
  //{ prop: "sortCode", label: t("message.dictTypeInfo.sortCode") },
  { prop: "operation", label: t("message.commonBtn.oper"), fixed: "right", minWidth: 100 }
];

const openEditDictType = (type: string, dictTypeRow: DictType.SysDictType) => {
  editDictTypeRef.value?.openDialog(type, dictTypeRow);
};

const delDictType = (dictTypeRow: DictType.SysDictType) => {
  ElMessageBox.confirm(`此操作将永久删除字典类型：“${dictTypeRow.name}”，是否继续?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      const [err] = await feature(dictTypeApi.delete({ id: dictTypeRow.id }));
      if (err) {
        NotificationError(err.message);
      } else {
        NotificationSuccess("删除成功");
        refreshDictType();
      }
    })
    .catch();
};

const refreshDictType = async () => {
  await dictTypeProTableRef.value?.getTableList();
};

const resetDictType = () => {
  dictTypeInitParam.name = "";
  choseDictType.value = {};
  dictTypeProTableRef.value?.reset();
};

// 单击行
const rowClick = (row: DictType.SysDictType, column: TableColumnCtx<DictType.SysDictType>) => {
  if (column.property == "radio" || column.property == "operation") return;
  dictDataInitParam.dictDataName = "";
  choseDictType.value = row;
  refreshDictData();
};

const dictDataCallback = (queryRes: UnifyResult<SqlSugarPagedList<DictData.SysDictData>>) => {
  const data = queryRes.data;
  return {
    items: data.items,
    totalCount: data.totalCount,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize
  };
};
const dictDataColumns: ColumnProps<DictData.SysDictData>[] = [
  { prop: "name", label: t("message.dictDataInfo.name") },
  { prop: "value", label: t("message.dictDataInfo.value") },
  { prop: "tagType", label: t("message.dictDataInfo.tagType") },
  { prop: "tagSize", label: t("message.dictDataInfo.tagSize"), align: "center" },
  //{ prop: "remark", label: t("message.dictDataInfo.remark") },
  {
    prop: "tag",
    label: t("message.dictDataInfo.tagEffect"),
    render: scope => {
      return (
        <el-tag size={scope.row.tagSize} type={scope.row.tagType}>
          {scope.row.name}
        </el-tag>
      );
    }
  },
  { prop: "sortCode", label: t("message.dictDataInfo.sortCode") },
  { prop: "operation", label: t("message.commonBtn.oper"), fixed: "right" }
];
const dictDataInitParam = reactive({ dictDataName: "" });

const refreshDictData = async () => {
  await dictDataProTableRef.value?.getTableList();
};

const resetDictData = () => {
  dictDataInitParam.dictDataName = "";
  choseDictType.value = {};
  dictDataProTableRef.value?.clearTable();
};

const getDictData = async (params: any) => {
  if (!choseDictType.value.id && !dictDataInitParam.dictDataName) return null;
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.dictTypeId = choseDictType.value.id;
  newParams.dictDataName = dictDataInitParam.dictDataName;
  return await dictDataApi.page(newParams);
};
const delDictData = (dictdataRow: DictData.SysDictData) => {
  ElMessageBox.confirm(`此操作将永久删除字典：“${dictdataRow.name}”，是否继续?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      const [err] = await feature(dictDataApi.delete({ id: dictdataRow.id }));
      if (err) {
        NotificationError(err.message);
      } else {
        NotificationSuccess("删除成功");
        refreshDictData();
      }
    })
    .catch();
};

const openEditDictDataByTypeRow = (dictTypeRow: DictType.SysDictType) => {
  editDictDataRef.value?.openDialog("add", {}, dictTypeRow);
};

const openEditDictData = (type: string, dictDataRow: DictData.SysDictData) => {
  if (!choseDictType.value.id) {
    NotificationWarning("请先点击字典类型");
    return;
  }
  editDictDataRef.value?.openDialog(type, dictDataRow, choseDictType.value);
};
</script>
<style lang="scss" scoped>
.grid {
  display: grid;
  grid-template-columns: 4fr 6fr;
  grid-gap: 10px;
}
.left-table {
  grid-column: 1 / 2;
}
.right-table {
  grid-column: 2 / 3;
}
.align-container {
  display: flex;
  align-items: center; /* 垂直居中 */
}
</style>
